import React, {useEffect, useState} from 'react';
import {bindActionCreators} from "redux";
import {connect} from "react-redux";
import {Modal, ModalHeader, ModalBody, ModalFooter, Col, Row, Button} from "reactstrap";
import {createSchedule, getScheduleById, getSchedules} from "../../../../../redux/actions/schedules";
import FullSpinnerDimming from "../../../../../components/@vuexy/spinner/Full-spinner-dimming";
import {setFieldData} from "../../../../../redux/actions/helper";
import {CLEAR_SCHEDULE, SET_SCHEDULE_FIELD, SET_SCHEDULE_VALUE} from "../../../../../redux/constants/schedules";
import Select from "react-select";
import Hotel from "./Forms/Hotel";
import Flight from "./Forms/Flight";
import Todo from "./Forms/Todo";
import Travel from "./Forms/Travel";
import Passengers from "./Components/Passengers";

const Forms = props => {
  const {scheduleId, eventId, getScheduleById, reqParams, getSchedules, schedule, spinner, isOpenModal, setFieldData, schedulableType, createSchedule} = props
  const [nameValid, setNameValid] = useState(false)
  const [companyValid, setCompanyValid] = useState(false)
  const [validatePassengers, setValidatePassengers] = useState([]);

  const schedulable_types = [
    {value: 'Todo', label: 'Добавить дело'},
    {value: 'Flight', label: 'Добавить рейс'},
    {value: 'Hotel', label: 'Добавить жилье'},
    {value: 'Travel', label: 'Добавить поездку'},
  ]

  const schedulables = {
    Todo: {description: '', header: 'Добавить дело'},
    Flight: {
      company: '',
      departure: null,
      arrival: null,
      number: '',
      header: 'Добавить рейс',
      passengers: 'Пассажиры',
      numberDesc: '№ билета'
    },
    Hotel: {
      address: null,
      phone: '',
      header: 'Добавить жилье',
      passengers: 'Гости и жильцы',
      numberDesc: 'номер брони'
    },
    Travel: {
      transport: 'car',
      departure: null,
      arrival: null,
      number: '',
      phone: '',
      name: '',
      header: 'Добавить поездку',
      passengers: 'Пассажиры',
      numberDesc: '№ билета'
    }
  }

  const validatePass = () => {
    let passengers = [];
    schedule.passengers.map((value, id) => {
      if (!value.name)
        passengers.push(id)
    })
    setValidatePassengers(passengers)
    return passengers
  }

  const typeChange = (e) => {
    if (!scheduleId) {
      setFieldData(SET_SCHEDULE_FIELD, 'schedulable_type', e.value)
      setFieldData(SET_SCHEDULE_FIELD, 'schedulable', schedulables[e.value])
    }
  }
  const toggle = () => {
    setFieldData(SET_SCHEDULE_VALUE, 'isOpenModal', false)
    setFieldData(SET_SCHEDULE_VALUE, 'schedule_id', null)
  }

  const Save = () => {
    let valid = false;
    if (!schedule.name) {
      valid = true;
      setNameValid(true)
    }

    if (schedulableType === 'Flight' && !schedule.schedulable.company) {
      valid = true;
      setCompanyValid(true)
    }

    if (schedulableType !== 'Todo' && validatePass().length) valid = true

    if (valid) return

    createSchedule(schedule, scheduleId, eventId)

  }

  useEffect(() => {
    if (scheduleId) {
      getScheduleById(scheduleId, reqParams)
    } else {
      setFieldData(SET_SCHEDULE_FIELD, 'schedulable', schedulables['Todo'])
    }
    return () => {
      setFieldData(CLEAR_SCHEDULE, 'schedule', {})
      getSchedules({...reqParams, event_id: eventId})
    }
  }, [])


  return (
    <React.Fragment>
      {spinner.includes('schedule-modal') && <FullSpinnerDimming/>}
      <Modal
        toggle={toggle}
        isOpen={isOpenModal}
        className="modal-lg"
      >
        <ModalHeader toggle={toggle}>
          {schedulables[schedulableType].header}
        </ModalHeader>
        <ModalBody>
          <div className="schedule-modal-body">
            <Row className="tab-info-item">
              <Col md={5} className="align-self-center mt-1">
                <input placeholder={'Название'}
                       onChange={e => {
                         nameValid && setNameValid(false)
                         setFieldData(SET_SCHEDULE_FIELD, 'name', e.target.value)
                       }}
                       value={schedule.name}
                       className={`schedule-item schedule-input ${nameValid ? 'custom-input-invalid' : ''}`}/>
              </Col>
              <Col md={7} className="align-self-center mt-1">
                <Select
                  className={`schedule-item schedule-input-select`}
                  classNamePrefix="dark_select"
                  value={{value: schedulableType, label: schedulables[schedulableType].header}}
                  options={schedulable_types}
                  isSearchable={false}
                  onChange={typeChange}
                  name='typesList'
                  isDisabled={scheduleId}
                />
              </Col>
            </Row>
            {
              schedulableType === 'Todo' &&
              <Todo tag={schedulableType} schedule={schedule} scheduleId={scheduleId}/>
            }
            {
              schedulableType === 'Flight' &&
              <Flight companyValid={companyValid} setCompanyValid={setCompanyValid} tag={schedulableType}
                      schedule={schedule} scheduleId={scheduleId}/>
            }
            {
              schedulableType === 'Hotel' &&
              <Hotel tag={schedulableType} schedule={schedule} scheduleId={scheduleId}/>
            }
            {
              schedulableType === 'Travel' &&
              <Travel tag={schedulableType} schedule={schedule} scheduleId={scheduleId}/>
            }

            {
              schedulableType !== 'Todo' &&
              <Passengers validatePassengers={validatePassengers} setValidatePassengers={setValidatePassengers}
                          numberDesc={schedulables[schedulableType].numberDesc}
                          title={schedulables[schedulableType].passengers}/>
            }
          </div>
        </ModalBody>
        <ModalFooter>
          <Button.Ripple color="danger" className="btn-uppercase" onClick={toggle}>
            Отменить
          </Button.Ripple>
          {
            scheduleId ? <Button.Ripple
                color="primary"
                className="btn-uppercase"
                onClick={Save}
              >
                Сохранить
              </Button.Ripple>
              :
              <Button.Ripple
                color="primary"
                className="btn-uppercase"
                onClick={Save}
              >
                Добавить
              </Button.Ripple>
          }
        </ModalFooter>
      </Modal>
    </React.Fragment>
  )
    ;

}

const mapStateToProps = state => ({
  scheduleId: state.schedules.schedule_id,
  reqParams: state.schedules.reqParams,
  schedule: state.schedules.schedule,
  isOpenModal: state.schedules.isOpenModal,
  spinner: state.helper.spinner,
  schedulableType: state.schedules.schedule.schedulable_type,
});
const mapDispatchToProps = dispatch => bindActionCreators({
  getScheduleById,
  setFieldData,
  createSchedule,
  getSchedules
}, dispatch);

export default connect(mapStateToProps, mapDispatchToProps)(Forms);
